package com.dongdongqiang.common.base;

import com.dongdongqiang.common.query.GenericQueryDAO;
import com.dongdongqiang.common.query.PageSearchForm;
import com.dongdongqiang.common.query.QueryException;
import com.dongdongqiang.daogenerator.DDQDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 基本Service
 * Created by ZZB on 2017/9/4.
 */
public abstract class BaseService <T extends BaseEntity> {
    @Autowired
    private DDQDAO ddqdao;
    @Autowired
    private GenericQueryDAO genericQueryDAO;

    private Class<T> getClazz(){
        return (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    private Connection getConnection(){
        DataSource dataSource = ddqdao.getDataSource();
        Connection connection = DataSourceUtils.getConnection(dataSource);
        return connection;
    }
    /**
     * 插入实体
     */
    public int insert(T t, String creator){
        if(t.getId() == null){
            t.setId(UUID.randomUUID().toString());
        }
        t.setCreator(creator);
        t.setCreateTime(new Date());
        t.setUpdater(creator);
        t.setUpdateTime(new Date());
        t.setActivate(true);
        return ddqdao.insert(t,getConnection());
    }

    /**
     * 更新实体
     */
    public int update(T t , String updater){
        t.setUpdater(updater);
        t.setUpdateTime(new Date());
        return ddqdao.update(t,getConnection());
    }

    /**
     * 删除
     */
    public int delete (String id){
        return ddqdao.deleteByPk(id,getClazz(),getConnection());
    }

    /**
     * 通过id获取实体
     */
    public T get(String id ){
        return ddqdao.getBy(id, getClazz(),getConnection());
    }

    /**
     * 恢复记录
     */
    public int recovery(String id ,String operator){
        return ddqdao.updateField(id,getClazz(),"activate",true,getConnection());
    }

    /**
     * 回收记录
     */
    public int trash(String id ,String operator){
        return ddqdao.updateField(id,getClazz(),"activate",false,getConnection());
    }

    /**
     * 通过字段查询列表
     */
    public List<T> queryBy(String field , Object value ){
        return ddqdao.queryBy(field, value, getClazz(), getConnection());
    }

    public BasePage<T> queryPage(String querySql, int page, int pageSize, Object... params) throws QueryException{
        return genericQueryDAO.queryPage(querySql, getClazz(), page, pageSize, params);
    }

    public <S extends PageSearchForm> BasePage<T> queryPage(S searchForm){
        return genericQueryDAO.queryPage(searchForm, getClazz());
    }
}
